package net.blogways.ordermgr.mail.factory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class TemplateFactory {

  // 日志
  private static Logger log = LoggerFactory.getLogger(TemplateFactory.class);

  // 模板文件路径(一般使用类路径)
  private static String templatePath = "/ftl";

  // 模板文件编码
  private static final String ENCODING = "UTF-8";

  // 模板文件生成读取配置
  private static Configuration config = new Configuration();

  // 邮件模板缓存
  private static Map<String, Template> cacheMap = new HashMap<String, Template>();

  //初始化类模板路径
  static {
    config.setClassForTemplateLoading(TemplateFactory.class, templatePath);
  }

  public static String printContextToTemplate(Map map, String templateName) throws IOException, TemplateException {
    Template temp = getTemplateByTemplateName(templateName);
    temp.setEncoding(ENCODING);
    Writer out = new StringWriter(2048);
    temp.process(map, out);
    String body = out.toString();
    return body;
  }

  /**
   * 根据模板名获取模板
   * @param templateName 模板名
   * @return
   * @throws IOException
   */
  public static Template getTemplateByTemplateName(String templateName) throws IOException {
    if (cacheMap.containsKey(templateName)) {
      return cacheMap.get(templateName);
    }
    Template template = config.getTemplate(templateName,ENCODING);
    cacheMap.put(templateName, template);
    return template;
  }
}
